package com.topisv.tms.service.baseusers;

import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.topisv.tms.entity.BaseUsers;
import com.topisv.tms.entity.Task;
import com.topisv.tms.repository.BaseUsersDao;
import com.topisv.tms.repository.TaskDao;
import org.springside.modules.persistence.DynamicSpecifications;
import org.springside.modules.persistence.SearchFilter;
import org.springside.modules.persistence.SearchFilter.Operator;

//Spring Bean的标识.
@Component
// 默认将类中的所有public函数纳入事务管理.
@Transactional(readOnly = true)
public class BaseUsersService {

	private BaseUsersDao baseUsersDao;

	public BaseUsers getBaseUsers(Long id) {
		return baseUsersDao.findOne(id);
	}

	@Transactional(readOnly = false)
	public void saveBaseUsers(BaseUsers entity) {
		baseUsersDao.save(entity);
	}

	@Transactional(readOnly = false)
	public void deleteBaseUsers(Long id) {
		baseUsersDao.delete(id);
	}

	public List<BaseUsers> getAllBaseUsers() {
		return (List<BaseUsers>) baseUsersDao.findAll();
	}

	public Page<BaseUsers> getBaseUsers(Long baseUsersId, Map<String, Object> filterParams, int pageNumber, int pageSize,
			String sortType) {
		PageRequest pageRequest = buildPageRequest(pageNumber, pageSize, sortType);
		return baseUsersDao.findAll(pageRequest);
	}

	/**
	 * 创建分页请求.
	 */
	private PageRequest buildPageRequest(int pageNumber, int pagzSize, String sortType) {
		Sort sort = null;
		if ("auto".equals(sortType)) {
			sort = new Sort(Direction.DESC, "id");
		} else if ("title".equals(sortType)) {
			sort = new Sort(Direction.ASC, "title");
		}

		return new PageRequest(pageNumber - 1, pagzSize, sort);
	}

	/**
	 * 创建动态查询条件组合.
	 */
	private Specification<BaseUsers> buildSpecification(Long baseUsersId, Map<String, Object> filterParams) {
		Map<String, SearchFilter> filters = SearchFilter.parse(filterParams);
		filters.put("user.id", new SearchFilter("user.id", Operator.EQ, baseUsersId));
		Specification<BaseUsers> spec = DynamicSpecifications.bySearchFilter(filters.values(), BaseUsers.class);
		return spec;
	}

	@Autowired
	public void setBaseUsersDao(BaseUsersDao baseUsersDao) {
		this.baseUsersDao = baseUsersDao;
	}
}
